package com.xiaohudie.JDBC;

import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

/**
 * @Author xiao hu die
 * @Date 2022/3/13 14:12
 * @Version 1.0
 */
/**JDBC开启事务*/
public class TestJdbcShiWu {
 public static void main(String[] args) throws Exception {
  Properties properties =new Properties();
  properties.load(new FileReader("src//dp.properties"));
  String driver = properties.getProperty("driver");
  String user = properties.getProperty("user");
  String url = properties.getProperty("url");
  String password = properties.getProperty("password");
  Connection connection =null;
  PreparedStatement preparedStatement =null;
  ResultSet resultSet =null;
  /**注册驱动*/
  try {
   Class.forName(driver);
   /**获取连接*/
   connection = DriverManager.getConnection(url, user, password);
   /**关闭JDBC自动提交
    * 开启事务*/
   connection.setAutoCommit(false);
   /**定义sql语句*/
   String UpdateSql = "UPDATE user SET name =? where id =? ";
   /**先编译*/
   preparedStatement = connection.prepareStatement(UpdateSql);
   /**再赋值*/
   preparedStatement.setString(1,"刘碟蝶");
   preparedStatement.setInt(2,15);
   int i = preparedStatement.executeUpdate();
   /**再执行*/
   TimeUnit.SECONDS.sleep(10);
   preparedStatement.setString(1,"陈唯怡怡");
   preparedStatement.setInt(2,16);
   int i1 = preparedStatement.executeUpdate();
   System.out.println(i1+i ==2?"更换成功" :"跟换失败");
   connection.commit();
  }finally {
   if (resultSet!=null){
    resultSet.close();
   }
   if (preparedStatement!=null){
    preparedStatement.close();
   }
   if (connection!=null){
    /**添加回滚*/
    connection.rollback();
    connection.close();
   }
  }
 }
 }

